package com.cmict.data.system.dal.redis.auth;


import com.cmict.data.framework.common.util.json.JsonUtils;
import com.cmict.data.framework.security.config.SecurityProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

import static com.cmict.data.system.dal.redis.RedisKeyConstants.LOCK_USER;


/**
 * {@link LoginUser} 的 RedisDAO
 *
 * @author awesome
 */
@Repository
public class LoginLockRedisDAO {


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private SecurityProperties securityProperties;

    public String get(String tenantId,String username,String clientIp) {
        String redisKey = formatKey(tenantId,username,clientIp);
        return JsonUtils.parseObject(stringRedisTemplate.opsForValue().get(redisKey), String.class);
    }

    public void set(String tenantId,String username,String clientIp ,Integer num) {
        String redisKey = formatKey(tenantId,username,clientIp);
        stringRedisTemplate.opsForValue().set(redisKey, JsonUtils.toJsonString(num),
                securityProperties.getLockTimeout());
    }

    public void delete(String tenantId,String username,String clientIp) {
        String redisKey = formatKey(tenantId,username,clientIp);
        stringRedisTemplate.delete(redisKey);
    }

    private static String formatKey(String tenantId,String username,String clientIp) {
        return String.format(LOCK_USER.getKeyTemplate(),username + ":" + clientIp);
    }

}
